import {
  All,
  Controller,
  Get,
  Post,
  Body,
  Query,
  Delete,
  ParseIntPipe,
  Put,
  Param,
  ValidationPipe,
  UseInterceptors,
  ClassSerializerInterceptor,
} from '@nestjs/common'
import PageParam from '@main/bo/PageParam'
import { QueryPageParamPipe } from '@main/pipe/PageParamPipe'
import { IdsParamPipe } from '@main/pipe/IdsParamPipe'
import { ApiOperation, ApiQuery, ApiTags, ApiOkResponse } from '@nestjs/swagger'
import { ApiResp } from '@main/bo/ApiResp'
import { GenericApiResponse } from '@main/bo/GenericApiResponse'
import ApiEntity from '@main/db/entity/ApiEntity'
import { ApiService } from '@main/service/ApiService'

@Controller('api')
@ApiTags('接口管理')
export class ApiController {
  constructor(private readonly service: ApiService) {}

  @Get('page')
  @ApiOperation({ summary: '分页查询' })
  @ApiQuery({ name: 'projectId', description: '项目id', type: 'number' })
  @ApiQuery({ name: 'current', description: '页号. 默认: 1', type: 'number' })
  @ApiQuery({ name: 'size', description: '每页记录条数. 默认: 15', type: 'number' })
  @GenericApiResponse(ApiEntity, true, true)
  async page(
    @Query(QueryPageParamPipe) pageParam: PageParam,
    @Query('projectId', ParseIntPipe) projectId: number,
    @Query('kw') kw: string
  ) {
    const ret = await this.service.page(projectId, pageParam.current, pageParam.size, kw)
    return ApiResp.success(ret)
  }

  @Post('add')
  @ApiOperation({ summary: '新增' })
  @GenericApiResponse(ApiEntity)
  @ApiOkResponse({ description: '执行成功', type: ApiResp })
  async add(
    @Body(
      new ValidationPipe({
        stopAtFirstError: true,
      })
    )
    data: ApiEntity
  ) {
    const id = await this.service.add(data)
    return ApiResp.success(id)
  }

  @Post(`copy-add/:id`)
  @ApiOperation({ summary: '复制新增' })
  @GenericApiResponse(ApiEntity)
  @ApiOkResponse({ description: '执行成功', type: ApiResp })
  async copyAdd(@Param('id', ParseIntPipe) id: number) {
    const newId = await this.service.copyAdd(id)
    return ApiResp.success(newId)
  }

  @Put('modify')
  @ApiOperation({ summary: '修改' })
  @ApiOkResponse({ description: '执行成功', type: ApiResp })
  async modify(
    @Body(
      new ValidationPipe({
        stopAtFirstError: true,
      })
    )
    data: ApiEntity
  ) {
    const updatedCount = await this.service.modify(data)
    return ApiResp.success(updatedCount)
  }

  @Delete('remove')
  @ApiOperation({ summary: '删除' })
  @ApiOkResponse({ description: '执行成功', type: ApiResp })
  async remove(@Query(IdsParamPipe) ids: number[]) {
    return ApiResp.success(await this.service.remove(ids))
  }
}
